<template>
  <div id="app">
    <v-header/>
    <div class="box">
      <input type="text" v-model="choiceCityName" disabled>
      <button @click="toggle">请选择城市</button>
    </div>
    <mask-box @choosing="chooseResult" :message="maskMessage" v-if="maskShow" />
    <popup ref="popup" @popupHasShow="popupHasShow">
      <!-- <v-header @click.native="$refs.popup.hide()">
      </v-header> -->
      <search @txtdata="searchText" :clearText="clearSearch">
        <span @click="$refs.popup.hide()" style="font-size:25px;color:#fff;">&#10007;</span>
      </search>
      <transition name="list">
        <search-list v-if="associationShow" :searchListContent="searchListContent" @changeName="changeCity"></search-list>
      </transition>
      <scroll ref="suggest" :data="cityList" :probeType="3" :listenScroll="true" @distance="distance" @scrollStore="scrollStore">
          <div slot="scroll">
            <position-box :chooseCity="choiceCityName" :orientate="nowCity" :historyCityArr="historyCityArr" @changeCity="changeCity"></position-box>
            <city-list :cityList="cityList" :elementIndex="elementIndex" @changeCity="changeCity" @singleLetter="singleLetter"></city-list>
          </div>
          <nav-list ref="navList" :navList="cityIndexList" @toElement="toElement" :flagText="flagText"></nav-list>
      </scroll>
    </popup>
    <transition name="flag">
     <div class="nowFlag" v-if="flag">{{flagText}}</div>
    </transition>
  </div>
</template>

<script>
import axios from "axios";
import { getSearchList } from "./common/js/search";
import { getDistance } from "./common/js/dom";

import Header from "./components/Header/Header.vue";
import Popup from "./components/Popup/Popup.vue";
import MaskBox from "./components/Mask/MaskBox.vue";
import Scroll from "./components/Scroll/Scroll.vue";
import PositionBox from "./components/PositionBox/PositionBox.vue";
import CityList from "./components/CityList/CityList.vue";
import NavList from "./components/NavList/NavList.vue";
import Search from "./components/Search/Search";
import SearchList from "./components/SearchList/SearchList";
export default {
  name: "App",
  components: {
    "v-header": Header,
    "mask-box": MaskBox,
    Popup,
    Scroll,
    PositionBox,
    CityList,
    NavList,
    Search,
    SearchList
  },
  data() {
    return {
      nowCity: "", //当前所在城市
      choiceCity: "", //点击即将查看的城市
      choiceCityName: "", //选择查看的城市
      historyCityArr: [], //查看历史记录
      cityList: [], //城市列表
      cityIndexList: ["顶"], //右边导航栏列表
      maskShow: false, //弹窗是否弹出
      maskMessage: "", //弹窗展示的信息
      associationShow: false, //是否开启联想展示框
      searchListContent: [], //搜索页的内容数组
      clearSearch: false, //是否清除输入框的文字
      elementIndex: "", //navList 点击的index
      arrHeight: [], //高度数组
      flag: false, //字母牌是否显示
      flagText: "顶" //字母牌显示的文字
    };
  },
  created() {
    this.getNowCity();
    this.getCityList();
  },
  mounted() {},
  computed: {
    // 如果没有选择地址，默认切换到定位所在地址
    chooseCity() {
      return this.choiceCityName ? this.choiceCityName : this.nowCity;
    }
  },
  methods: {
    // 定位当前所在城市
    getNowCity() {
      this.getCity();
      this.getHistory();
      axios.get("http://localhost:1234/nowcity").then(
        res => {
          this.nowCity = res.data.city;
          if (!this.choiceCity && !this.choiceCityName) {
            this.choiceCity = this.choiceCityName = this.nowCity;
          }
        },
        () => {
          this.nowCity = "北京";
          if (!this.choiceCity && !this.choiceCityName) {
            this.choiceCity = this.choiceCityName = this.nowCity;
          }
        }
      );
    },
    //获取城市列表
    getCityList() {
      axios.get("http://localhost:1234/").then(res => {
        this.cityList = res.data.openCityList;
        this.getDomHeight();
        this.cityList.map(item => {
          this.cityIndexList.push(item[0]);
        });
      });
    },
    // 存到本地
    setHistory(arr) {
      localStorage.setItem("historyCityArr", arr);
    },
    // 从本地取
    getHistory() {
      let history = localStorage.getItem("historyCityArr");
      if (!history) {
        this.historyCityArr = [];
      } else {
        this.historyCityArr = history.split(",");
      }
    },
    // 存到本地，正在查看的城市
    setCity(name) {
      localStorage.setItem("seeCity", name);
    },
    // 从本地取，正在查看的城市
    getCity() {
      let name = localStorage.getItem("seeCity");
      if (!name) {
        this.choiceCity = this.choiceCityName = "";
      } else {
        this.choiceCity = this.choiceCityName = name;
      }
    },
    // 搜索框内容
    searchText(text) {
      if (text.length === 0) {
        this.associationShow = false;
        return false;
      }
      this.clearSearch = false;
      this.associationShow = true;
      this.searchListContent = getSearchList(text, this.cityList);
    },
    //改变城市
    changeCity(name) {
      if (this.choiceCityName === name) {
        this.associationShow = false; // 关闭搜索框（在搜索状态下）
        this.clearSearch = true; // 清除输入框的字（在搜索状态下）
        return false;
      } else {
        //选择的城市的名字
        this.choiceCity = name;
        this.maskMessage = `你确定要选择${name}吗？`;
        this.maskShow = true;
      }
    },
    //是否确认切换定位
    chooseResult(res) {
      if (!res) {
        this.maskClose(); // 不切换，仅关闭弹窗
        return;
      }
      this.choiceCityName = this.choiceCity;
      this.local();
      this.associationShow = false; // 关闭搜索框（在搜索状态下）
      this.clearSearch = true; // 清除输入框的字（在搜索状态下）

      // 当确认后滚动到顶部
      this.$refs.suggest.scrollTo(0, 0, 200);
      this.maskClose();
    },
    // 关闭mask
    maskClose() {
      this.maskShow = false;
    },
    // 根据定位确定加缓存
    local() {
      if (this.choiceCityName !== this.nowCity) {
        this.historyCityArr.unshift(this.choiceCityName);
      }
      this.historyCityArr = this.historyCityArr.slice(0, 2);
      this.setCity(this.choiceCityName);
    },
    // 点击右边nav，向citylist组件传值
    toElement(text) {
      if (text === "顶") {
        this.$refs.suggest.scrollTo(0, 0, 200);
      }
      this.elementIndex = text;
    },
    // 滚动到相应的dom节点
    singleLetter(dom) {
      this.$refs.suggest.scrollToElement(dom, 200, false, false);
    },
    toggle() {
      this.$refs.popup.show();
    },
    // 捕获popup显示动作
    popupHasShow(val) {
      setTimeout(() => {
        this.$refs.suggest.$el.style.border = "1px solid #e6e6e6";
        this.$refs.suggest.$el.style.borderTop = "none";
      }, 500);
    },
    choosing(msg) {
      this.maskShow = false;
    },
    distance(val) {
      for (let i = 0, len = this.arrHeight.length; i < len; i++) {
        if (val < this.arrHeight[i]) {
          this.flagText = this.cityIndexList[i];
          return;
        }
      }
    },
    // 是否显示字母牌
    scrollStore(val) {
      this.flag = val;
    },
    // 计算每一部分到顶端的距离
    getDomHeight() {
      let arr = getDistance(this.cityList);
      arr.unshift(250); // 向开始添加顶端的250px的距离
      let i = 0;
      arr.map(val => {
        i = i + val;
        this.arrHeight.push(i);
      });
    }
  },
  watch: {
    historyCityArr(val) {
      this.setHistory(val);
    }
  }
};
</script>

<style lang="scss">
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

input,
button {
  border: none;
  outline: none;
}

button {
  position: relative;
  &::after {
    content: "";
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    background-color: black;
    opacity: 0;
  }
  &:active::after {
    opacity: 0.4;
  }
}

input[disabled] {
  background-color: rgba(0, 0, 0, 0.05);
}

.clearfix {
  overflow: hidden;
  /* BFC (block formatting context)*/
  _zoom: 1;
}

a {
  text-decoration: none;
}

html,
body {
  width: 100%;
  height: 100%;
}

#app {
  width: 100%;
  height: 100%;
  font-size: 16px;
  overflow: scroll;
  -webkit-overflow-scrolling: touch;
  box-sizing: border-box;
  font-family: "Avenir", Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
}

.box {
  $height: 50px;
  width: 100%;
  height: $height;
  margin-top: $height;
  input {
    width: 40%;
    height: 100%;
    text-align: center;
    border: 1px solid silver;
    border-radius: 5px;
    background-color: #fff;
    margin-left: 10px;
  }
  button {
    width: 40%;
    height: 100%;
    border-radius: 5px;
    color: #fff;
    font-size: 18px;
    background-color: #4395ff;
  }
}
.nowFlag {
  width: 50px;
  height: 50px;
  background-color: #4395ff;
  color: #fff;
  font-size: 30px;
  font-weight: 900;
  line-height: 50px;
  text-align: center;
  position: absolute;
  top: 60px;
  left: 50%;
  margin-left: -25px;
}
.list-enter-active,
.list-leave-active {
  transition: all 0.5s;
}
.list-enter {
  opacity: 0;
}
.list-leave-to {
  transform: scale(0, 0);
  opacity: 0;
}
.flag-leave-active,
.flag-enter-active {
  transition: all 1s;
}
.flag-leave-to {
  opacity: 0;
}
</style>
